<?php

namespace App\Http\Controllers\Frontend\V10\Users;

use App\Events\AuthStepEvent;
use App\Exceptions\GeneralException;
use App\Facades\SamLogFacade;
use App\Http\Controllers\Controller;
use App\Http\Requests\Frontend\V10\Users\UserChooseCreditCardStoreRequest;
use App\Models\UserAuthStepEventLog;
use App\Models\UserBankCard;
use App\Models\UserChooseCreditCard;
use App\Models\UserLoanRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class UserChooseCreditCardController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }

    /**
     * Description:记录用户选择的信用卡
     * Author: Sam
     * DateTime: 2019/1/4 19:41
     * @param UserChooseCreditCardStoreRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function store(UserChooseCreditCardStoreRequest $request)
    {

        $user = Auth::user();
        $params = $this->extractInputFromRules($request,$request->rules());
        $bank_card = UserBankCard::find($params['bank_card_id']);
        if (!$bank_card){
            SamLogFacade::debug("用户【{$user->id}】选择信用卡【{$params['bank_card_id']}】失败，找不到信用卡信息");
            return failed('信用卡信息有误');
        }
        $params['user_id'] = $user->id;
        $loan = UserLoanRequest::where(['current'=>UserLoanRequest::CURRENT_NOW,'user_id'=>$user->id])->orderByDesc('id')->firstOrFail();
        DB::beginTransaction();
        try{
            $loan->credit_card_choice_id = $params['bank_card_id'];
            $loan->save();
            $log = [
                'uid'=>$user->id,
                'step_id'=>$params['bank_card_id'],
                'type'=>UserAuthStepEventLog::STEP_BIND_CREDIT,
                'loan_request_id'=>$loan->id,
            ];
            event(new AuthStepEvent($log));
            DB::commit();
        }catch (\Exception $exception){
            Log::error("选择信用卡操作失败：".$exception->getMessage());
            DB::rollBack();
            throw new GeneralException($exception->getMessage(),500);
        }
        return success([]);
    }
}
